<template>
  <div class="normalMaintenanceStandardDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :creatInfo="formData"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title-code">{{ `巡视计划 ${formData.code || ""}` }}</span>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="titleEdit"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend">标题</template
            ></el-input
          >
        </div>
      </div>
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title">
            <span class="titleLine"></span>
            基本信息
          </template>
          <basicInfo
            :allInfo="formData"
            :unEdit="unEdit"
            :pageType="pageType"
            @unTimeRelease="unTimeRelease"
            ref="basicInfo"
          />
        </el-collapse-item>
        <el-collapse-item name="2">
          <template slot="title">
            <span class="titleLine"></span>
            巡视路线
          </template>
          <patrolRoute
            :pointList="formData.rels"
            :unEdit="unEdit"
            ref="patrolRoute"
          />
        </el-collapse-item>
        <el-collapse-item name="3" v-if="isShowTimer">
          <template slot="title">
            <span class="titleLine"></span>
            定时器信息
          </template>
          <timerInfo
            ref="timerInfo"
            :disabled="unChangeable"
            :cronTask="formData.cronTask || {}"
          ></timerInfo>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      title="已下发工单"
      :show.sync="show"
      v-if="show"
      @doClose="() => (show = false)"
      noFootBtn
      :fullscreen="true"
      appendTobody
    >
      <orderList showType="query" :planId="formData.id" ref="orderList" />
    </dialogPublic>
  </div>
</template>
<script>
import {
  queryPatrolPlanDetail,
  addOrUpdatePatrolPlan,
  deletePatrolPlan,
  startOrStopPlan,
  issuePlan,
} from "@/api/productionPlan/patrolPlan.js";
import basicInfo from "./basicInfo.vue";
import patrolRoute from "./patrolRoute.vue";
import timerInfo from "../../maintenancePlan/timerInfo.vue";
import orderList from "@/views/orderManagement/patrolOrder/index.vue"
export default {
  components: {
    basicInfo,
    patrolRoute,
    timerInfo,
    orderList
  },
  data() {
    return {
      activeNames: ["1", "2", "3"],
      pageType:"",
      titleName: "",
      show:false,
      showInput: false,
      isShowTimer: true, //是否展示定时器信息
      hideBtn: false,
      titleEdit: true,
      state: -1,
      creatInfo: {},
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
        {
          text: "已下发工单",
          methods: () => {
            this.show = true;
          },
        },
      ],
      basicConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "适用范围:",
            prop: "appName",
            type: "text",
            trigger: "change",
            span: 8,
            required: true,
            disabled: true,
            methods: (val) => {
              this.changeType = val.value;
            },
          },
          {
            label: "设备分类:",
            prop: "typeName",
            idsStr: "typeId",
            type: "deviceClassify",
            required: true,
            disabled: false,
            span: 8,
          },
        ],
      },
      formData: {},
      checkItemList: [],
      paramsItemList: [],
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "启用",
          icon: "el-icon-video-play",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.state == 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("enable"),
          methods: () => {
            this.enablePlan();
          },
        },
        {
          text: "手动下发",
          icon: "el-icon-refresh",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.state == 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("issue"),
          methods: () => {
            this.issued();
          },
        },
        {
          text: "停用",
          icon: "el-icon-video-pause",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.state == 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("deactivate"),
          methods: () => {
            this.DeactivatePlan();
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) || this.state == 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide: ["perform", "details", "add"].includes(this.pageType) || this.state == 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    stepConfig() {
      let obj = {
        nowStep: this.state, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "已启用"],
      };
      return obj;
    },
    unChangeable() {
      return this.state == 1 || this.pageType == "detail";
    },
    unEdit() {
      return ["query", "detail"].includes(this.pageType) || this.state == 1;
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      let { id } = this.$route.query;
      if (id) {
        this.pageType = this.$store.getters.isBtnAuth("edit")
          ? "edit"
          : "detail";
        this.getDetails(id);
        if (this.pageType == "detail") {
          this.titleEdit = false;
        }
      } else {
        this.pageType = "add";
        this.showInput = true;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.showInput = true;
        this.$message.warning("标题不能为空");
      }
    },
    //是否定时下达
    unTimeRelease(val) {
      this.isShowTimer = !val;
    },
    //获取标准详情
    getDetails(id) {
      queryPatrolPlanDetail({ planId: id }).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          this.creatInfo = res.data;
          this.titleName = this.formData.name;
          this.state = this.formData.state;
          this.isShowTimer = this.formData.isTimer == 1 ? true : false;
          if (this.state) {
            this.hideBtn = true;
            this.titleEdit = false;
          } else {
            this.hideBtn = false;
            this.titleEdit = true;
          }
        }
      });
    },
    //启用
    enablePlan() {
      const params = {
        id: this.formData.id,
        startOrStop: true,
      };
      startOrStopPlan(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("启用成功");
          this.$utils.addOperateLog(this.formData.id, "启用了巡视计划");
          this.getDetails(this.formData.id);
          this.updateListData();
        }
      });
    },
    //停用
    DeactivatePlan() {
      const params = {
        id: this.formData.id,
        startOrStop: false,
      };
      startOrStopPlan(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("停用成功");
          this.$utils.addOperateLog(this.formData.id, "停用了巡视计划");
          this.getDetails(this.formData.id);
          this.updateListData();
        }
      });
    },
    //手动下发
    issued() {
      issuePlan({ id: this.formData.id }).then((res) => {
        if (res.code == 200) {
          this.$message.success("下发成功");
          this.$utils.addOperateLog(this.formData.id, "手动下发了巡视计划");
          this.updateListData();
        }
      });
    },
    //删除
    deleteId() {
      this.$confirm("确定要删除选中数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletePatrolPlan({ planId: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(this.formData.id, "删除了巡视计划");
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //保存正常维护标准
    async save() {
      try {
        let formData = await this.$refs.basicInfo.getBasicInfo();
        let pointList = this.$refs.patrolRoute.getPointList();
        if (this.titleName == "") {
          this.loseFocus();
        } else if (pointList.length == 0) {
          this.$message.warning("巡视点列表不能为空");
        } else {
          formData.name = this.titleName;
          formData.rels = pointList;
          formData.state = 0;
          if (formData.isTimer) {
            formData.cronTask = this.$refs.timerInfo.getTimeInfo();
          }
          let res = await addOrUpdatePatrolPlan(formData);
          this.$message.success(res.description);
          this.updateListData();
          if (this.pageType == "add") {
            this.$utils.addOperateLog(res.data.id, "新增了巡视计划");
            let obj = {
              id: res.data.id,
              pageType: "edit",
            };
            this.$router.push({
              query: obj,
            });
          } else {
            this.$utils.addOperateLog(this.formData.id, "修改了巡视计划");
            this.getDetails(this.formData.id);
          }
        }
      } catch (error) {
        this.$message.Warning(error);
      }
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.normalMaintenanceStandardDetails {
  // overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
}
</style>